// 2013-8-31下午06:32:49  net.betou.trade.admin.action.ProxyAct.java

package net.betou.trade.admin.action;

import static net.betou.common.page.SimplePage.cpn;
import static net.betou.common.page.SimplePage.cpnPageSize;

import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.betou.common.page.Pagination;
import net.betou.common.util.DataConvertUtils;
import net.betou.common.util.TradeUtils;
import net.betou.common.web.RequestUtils;
import net.betou.common.web.springmvc.RealPathResolver;
import net.betou.trade.action.abs.ActionSupport;
import net.betou.trade.entity.main.AgentAndAdmins;
import net.betou.trade.entity.main.AgentAndAdminsExt;
import net.betou.trade.entity.main.Picture;
import net.betou.trade.entity.main.Role;
import net.betou.trade.main.manager.PictureMng;
import net.betou.trade.main.manager.agencyorproxy.ProxyMng;
import net.betou.trade.main.manager.role.AgencyRoleMng;
import net.betou.trade.web.Messages;
import net.betou.trade.web.ResponseUtil;
import net.betou.trade.web.WebErrors;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 代理商Act
 * @author 叶装装
 */
@Controller
public class ProxyAct extends ActionSupport< AgentAndAdmins >{
	
	private static final Logger log = LoggerFactory.getLogger( ProxyAct.class );
	
	private static final String DIRECTORY = "proxy";
	
	@RequestMapping( "/proxy/v_list.jspx" )
	public String list( Integer pageSize, Integer pageNo, String filterStatus, String searchProperty, String searchValue, String orderProperty, String orderDirection, HttpServletRequest request, HttpServletResponse response, ModelMap model  ){
		
		pageSize = cpnPageSize( pageSize );
		pageNo = cpn( pageNo );
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request ); // 获取当前管理员
			
		Pagination pagination = mng.getPage( admin, searchProperty, searchValue, orderProperty, orderDirection, pageNo, pageSize, filterStatus );
		
		model.addAttribute( "admin", admin );
		
		paramToModel( model, pagination, null, pageSize, searchProperty, searchValue, orderProperty, orderDirection, filterStatus );
		return getListPage( );
	}
	
	@RequestMapping( "/proxy/v_add.jspx" )
	public String v_add( HttpServletRequest request, ModelMap model ){
		
		AgentAndAdmins user = TradeUtils.getAdmin( request ); // 获取当前管理员
		
		model.addAttribute( "admin", user );
		
		return getAddPage( );
	}
	
	@RequestMapping( "/proxy/o_save.jspx" )
	public String o_save( AgentAndAdmins bean, AgentAndAdminsExt ext,  String [] pic,  HttpServletRequest request, HttpServletResponse response, ModelMap model ){
		
		WebErrors errors = validateSave( bean, ext );
		
		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}
		
		// 获取推荐商
		AgentAndAdmins admin = mng.findByIntermediaName( ext.getRecommentAgent( ) ); 
		
		String ip = RequestUtils.getIpAddr( request );
		
		bean = mng.save( admin, ip, bean, ext, pic );
		
		logMng.operating( 0, request, Messages.LOG_PROXY, "id=" + bean.getId( ) + ",name=" + bean.getIntermediaName( ) );
		
		return "redirect:v_list.jspx";
	}
	
	/**
	 * 升级成为机构的时候,就显示机构和代理商角色
	 * @version 1.1
	 * @return
	 */
	@RequestMapping ("/proxy/v_edit.jspx" )
	public String v_edit( Integer id, HttpServletRequest request, ModelMap model ){

		WebErrors errors = validateUpdate( request, id );
		
		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}
		
		AgentAndAdmins bean = mng.findById( id );
		
		model.addAttribute( "bean", bean );
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request ); // 获取当前管理员
		
		AgentAndAdmins deepZeroAgency = null;
		
		// 代理商的话, 只能将代理商修改成自己添加的角色
		// 代理商的更新， 如果是机构的话，就应该查询出这个机构的所有角色
		// 如果只是代理商，就只查询出自己的角色
		if( admin.getSystem( ) ){
			if( bean.getDeep( ) == 0 ){ // deep为0，此时他的角色也会为机构角色。 所以就可以直接等于这个bean, 否则的话，就要查询出最顶级的
				deepZeroAgency = bean;
			}else{
				deepZeroAgency = mng.findById( DataConvertUtils.getInt( StringUtils.split( bean.getTopIntermedia( ), ",")[ 0 ] ) );
			}
			// 如果只是代理商后者机构，此时的admin就为自己的admin
		}
		
		List< Role > roleList = roleMng.list( admin, deepZeroAgency );
		// 编辑代理商的时候,不能包含系统管理员的
		// 如果不是机构并且不是系统管理员
		if( !admin.getAgencyOrProxy( ) && !admin.getSystem( ) ) {
			Set< Role > roles = admin.getRoles( );
			if( roles != null && roles.size( ) > 0 ){
				for( Iterator< Role > it = roles.iterator( ); it.hasNext( ); ){
					roleList.add( it.next( ) );
				}
			}
		}
		
		model.addAttribute( "roleList", roleList );
		model.addAttribute( "admin", admin ); // 仍然保留系统管理员,全部的角色信息
		
		return getUpdatePage( );
	}
	
	/**
	 * @return
	 */
	@RequestMapping ( "/proxy/o_update.jspx" )
	public String o_update( Boolean disabled, Integer id, String password, String mobile, String intermediaName, String email, Integer [ ] roleIds,  String [] pic, Integer[] picIds, AgentAndAdminsExt ext, HttpServletRequest request, ModelMap model ){
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		
		WebErrors errors = validateOUpdate( id, admin );
		
		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}
		
		AgentAndAdmins bean = mng.findBySelf( admin, id );
		
		bean = mng.update( disabled, password, email, mobile, intermediaName, bean, ext, roleIds, pic, picIds );
		
		logMng.operating( 1, request, Messages.LOG_PROXY, "id=" + bean.getId( ) + ",username=" + bean.getUsername( ));
		
		return "redirect:v_list.jspx";
	}
	
	@RequestMapping( "/proxy/o_delete.jspx" )
	public void o_delete( Integer [ ] ids, HttpServletResponse response, HttpServletRequest request ){
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		
		ResponseUtil util = validateDelete( ids, admin, response, request );

		if( util.hasResponse( ) ){
			util.renderJson( );
			return;
		}
		
//		Role[] roles = roleMng.findListByAdminIds( ids );//暂时先不删除创建的角色

		AgentAndAdmins [ ] beans = mng.deleteByIds( ids );
		
//		if(roles.length>0){//暂时先不删除创建的角色
//			Integer[] roleIds = buildIdArray(roles);
//			roleMng.deleteByIds(roleIds);
//		}

		for ( AgentAndAdmins bean : beans ){
			log.info( "delete Admin id={}", bean.getId( ) );
			
			logMng.operating( 2, request, Messages.LOG_PROXY, "id=" + bean.getId( ) + ",username=" + bean.getUsername( ));
		}

		util.addSuccessResponse( Messages.getDeleteSuccessMessage( beans.length ) );

		util.renderJson( );
		return;
	}
	
	@RequestMapping( "/proxy/o_delete_img.jspx" )
	public void o_delete( Integer id, HttpServletResponse response, HttpServletRequest request ){
		
		ResponseUtil util = ResponseUtil.create( response );

		Picture p = picMng.findById( id );
		
		if( p == null ){
			util.addErrorResponse( Messages.DATA_NOT_EXIST );
			util.renderJson( );
			return;
		}
		
		picMng.deleteById( id );
		
		String path = p.getPath( );
		String deletePath = realPath.get( path );
		
		File file = new File( deletePath );
		
		file.delete( );
		
		util.addSuccessResponse( Messages.DATA_DELETE_SUCCESS );

		util.renderJson( );
		return;
	}
	
	
	
	
	private ResponseUtil validateDelete( Integer [ ] ids, AgentAndAdmins admin, HttpServletResponse response, HttpServletRequest request ) {
		ResponseUtil util = ResponseUtil.create( response );

		if( ids == null || ids.length == 0 ){
			util.addErrorResponse( Messages.DATA_NOT_SELECT );
			return util;
		}

		for ( Integer id : ids ){
			AgentAndAdmins bean = mng.findBySelf( admin, id );
			
			if( bean == null ){
				util.addErrorResponse( admin.getSystem( ) ? Messages.DATA_NOT_EXIST : Messages.DATA_NOT_OPERATING );
				break;
			}
		}
		return util;
	}
	
	
	private WebErrors validateOUpdate( Integer id, AgentAndAdmins admin ){
		WebErrors errors = WebErrors.create( );
		
		if( id == null || id == 0 ){
			errors.addError( Messages.DATA_NOT_EXIST );
			return errors;
		}
		
		AgentAndAdmins bean = mng.findBySelf( admin, id );
		
		if( bean  == null ){
			errors.addError( Messages.DATA_NOT_OPERATING );
			return errors;
		}
		
		return errors;
		
	}
	/**
	 * 此处的判断为, 查找居间商,如果不是,则返回错误消息..
	 * 避免恶意ID传入信息被修改
	 * @param request
	 * @param id
	 * @return
	 */
	private WebErrors validateUpdate( HttpServletRequest request, Integer id ){
		WebErrors errors = WebErrors.create( );
		
		if( id == null || id == 0 ){
			errors.addError( Messages.DATA_NOT_EXIST );
			return errors;
		}
		
		AgentAndAdmins admin = mng.findProxy( id ) ;
		
		if( admin == null ){
			errors.addError( Messages.DATA_NOT_EXIST );
			return errors;
		}
		
		return errors;
			
	}
	
	private WebErrors validateSave( AgentAndAdmins bean, AgentAndAdminsExt ext ){
		WebErrors errors = WebErrors.create( );
		
		String recommentAgent = ext.getRecommentAgent( );
		
		if( StringUtils.isBlank( recommentAgent ) ){
			errors.addError( Messages.RECOMMENT_ACCOUNT_NOT_EXIST );
			return errors;
		}
		
		AgentAndAdmins admin = mng.findByIntermediaName( recommentAgent );
		
		if( admin == null ){
			errors.addError( Messages.RECOMMENT_ACCOUNT_NOT_EXIST );
			return errors;
		}
		
		return errors;
	}
	
	@Autowired
	private ProxyMng mng;
	
	@Autowired
	private AgencyRoleMng roleMng;
	
	@Autowired
	private PictureMng picMng;
	
	@Autowired
	private RealPathResolver realPath;
	
	@Override
	protected String getDirectory( ) {
		
		return DIRECTORY;
	}

}
